package com.cn.wanxi.io;

import com.cn.wanxi.dto.NewsModelDto;
import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.util.Common;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NewsIO {
    private String path = "D:\\step-three\\news.txt";
    private String[] result;

    public NewsIO() {
        writeNote();
        result = Common.readNote(path).split("%%");

    }

    private void writeNote() {
        File file = new File(path);
        try {
            OutputStream outputStream = new FileOutputStream(file);//如果我们地址不存在，会进行自动创建
            NewsModel newsModel = new NewsModel();
            outputStream.write(Arrays.toString(newsModel.newsHref).getBytes());
            outputStream.write("%%".getBytes());
            outputStream.write(Arrays.toString(newsModel.newsTime).getBytes());
            outputStream.write("%%".getBytes());
            outputStream.write(Arrays.toString(newsModel.newsTitle).getBytes());
            outputStream.write("%%".getBytes());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public NewsModelDto getFromNewsIO() {
        NewsModelDto newsModelDto = new NewsModelDto();
        newsModelDto.setNewsList(getNewsList());
        return newsModelDto;
    }

    private List<NewsModel> getNewsList() {
        String href = result[0];
        String newsTime = result[1];
        String newsTitle = result[2];
        href = Common.replace(href, "", "[", "]");
        newsTime = Common.replace(newsTime, "", "[", "]");
        newsTitle = Common.replace(newsTitle, "", "[", "]");
        String[] hrefs = href.split(",");
        String[] newsTitles = newsTitle.split(",");
        String[] newsTimes = newsTime.split(",");
        //得到新闻信息
        List<NewsModel> newsList = new ArrayList<>();
        for (int i = 0; i < newsTimes.length; i++) {
            NewsModel model = new NewsModel();//这个model用来封装每一个新闻数据
            model.setTitle(newsTitles[i]);
            model.setHref(hrefs[i]);
            model.setCreateTime(newsTimes[i]);
            newsList.add(model);
        }
        return newsList;
    }

}
